# -*- coding: utf-8 -*-
import sys
import warnings
warnings.filterwarnings('ignore')
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from urllib.parse import  urlencode
from common.helper import Helper


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "太平金生康瑞终身重大疾病保险"
    # 生产产品数据
    def genProductInfo(self):
        planI = {
            "planA":{
                # 年龄段
                "year":[str(i) for i in range(0,10)],
                #性别
                "gender":["M","F"],
                #保额
                "money":["200000"],
                #保障期限
                "expire":["终身"],
                #缴费间隔
                "interval":["10y","15y","20y"],
                #缴费方式
                "payType":["年缴"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(10, 40)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["200000","250000","300000"],
                # 保障期限
                "expire": ["终身"],
                # 缴费间隔
                "interval": ["10y", "15y", "20y"],
                # 缴费方式
                "payType": ["年缴"]
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(10, 40)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["200000", "250000", "300000"],
                # 保障期限
                "expire": ["终身"],
                # 缴费间隔
                "interval": ["10y", "15y", "20y"],
                # 缴费方式
                "payType": ["年缴"]
            },
            "planD":{
                # 年龄段
                "year": ["40"],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["100000", "150000", "200000", "250000", "300000"],
                # 保障期限
                "expire": ["终身"],
                # 缴费间隔
                "interval": ["10y", "15y", "20y"],
                # 缴费方式
                "payType": ["年缴"]

            },
            "planE": {
                # 年龄段
                "year": [str(i) for i in range(41,51)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["100000", "150000", "200000"],
                # 保障期限
                "expire": ["终身"],
                # 缴费间隔
                "interval": ["10y", "15y", "20y"],
                # 缴费方式
                "payType": ["年缴"]

            },
            "planF": {
                # 年龄段
                "year": [str(i) for i in range(51, 56)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["100000"],
                # 保障期限
                "expire": ["终身"],
                # 缴费间隔
                "interval": ["10y", "15y"],
                # 缴费方式
                "payType": ["年缴"]

            },
            "planG": {
                # 年龄段
                "year": [str(i) for i in range(56, 61)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000"],
                # 保障期限
                "expire": ["终身"],
                # 缴费间隔
                "interval": ["10y"],
                # 缴费方式
                "payType": ["年缴"]

            }

        }

        planII = {

            "planA":{
                # 年龄段
                "year":[str(i) for i in range(0,10)],
                #性别
                "gender":["M","F"],
                #保额
                "money":["200000"],
                #保障期限
                "expire":["终身"],
                #缴费间隔
                "interval":["120m","180m","240m"],
                #缴费方式
                "payType":["月缴"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(10, 40)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["200000","250000","300000"],
                # 保障期限
                "expire": ["终身"],
                # 缴费间隔
                "interval": ["120m", "180m", "240m"],
                # 缴费方式
                "payType": ["月缴"]
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(10, 40)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["200000","250000", "300000"],
                # 保障期限
                "expire": ["终身"],
                # 缴费间隔
                "interval": ["120m", "180m", "240m"],
                # 缴费方式
                "payType": ["月缴"]
            },
            "planD":{
                # 年龄段
                "year": ["40"],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["100000", "150000", "200000", "250000", "300000"],
                # 保障期限
                "expire": ["终身"],
                # 缴费间隔
                "interval": ["120m", "180m", "240m"],
                # 缴费方式
                "payType": ["月缴"]

            },
            "planE": {
                # 年龄段
                "year": [str(i) for i in range(41,51)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["100000", "150000", "200000"],
                # 保障期限
                "expire": ["终身"],
                # 缴费间隔
                "interval": ["120m", "180m", "240m"],
                # 缴费方式
                "payType": ["月缴"]

            },
            "planF": {
                # 年龄段
                "year": [str(i) for i in range(51, 56)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["100000"],
                # 保障期限
                "expire": ["终身"],
                # 缴费间隔
                "interval": ["120m", "180m"],
                # 缴费方式
                "payType": ["月缴"]

            },
            "planG": {
                # 年龄段
                "year": [str(i) for i in range(56, 61)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000"],
                # 保障期限
                "expire": ["终身"],
                # 缴费间隔
                "interval": ["120m"],
                # 缴费方式
                "payType": ["月缴"]

            }

        }
        for k in planI:
            for v in product(planI[k]["year"],planI[k]["gender"],planI[k]["money"],planI[k]["expire"],planI[k]["interval"],planI[k]["payType"]):
                self.mysql.cursor.execute( domain[self.name]["insert_sql"].format(
                    v[0],v[1],v[2],v[3],v[4],v[5]
                ))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(
                    v[0],v[1],v[2],v[3],v[4],v[5]
                ) )
        for k in planII:
            for v in product(planII[k]["year"],planII[k]["gender"],planII[k]["money"],planII[k]["expire"],planII[k]["interval"],planII[k]["payType"]):
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(
                    v[0], v[1], v[2], v[3], v[4], v[5]
                ))
                print(  domain[self.name]["insert_sql"].format(
                    v[0],v[1],v[2],v[3],v[4],v[5]
                ))
                self.mysql._conn.commit()

    #执行爬虫
    def requestJson(self,dt=None):
        if dt["payType"] == "年缴":
            print("/*~~~~年缴~~~~~~*/")
            if dt["interval"] == "10y":
                risk_code = "0110000318"
                productCode = "50000837"
            elif dt["interval"] == "15y":
                risk_code = "0110000331"
                productCode = "50000838"
            else:
                risk_code = "0110000333"
                productCode = "50000839"
            data = {

                "pageName": "productAdd",
                "goods_id": "62540",
                "merchant_id": "B2C",
                "toubaoli_money":"",
                "productCode": productCode,
                "productId": "f4bbe12e-4946-41c5-a6c2-454ee94ac339",
                "riskCode": risk_code,
                "productName": "太平金生康瑞终身重大疾病保险",
                "insuredPrice": "36.50",
                "insured.birthday":"",
                "templateType": "",
                "employee_id":"",
                "channel": "GWSC - MENU - M14",
                "empNo":"",
                "newsCode":"",
                "twoMonthInsuredPrice":"",
                "loginUserId":"",
                "insured.age": "0"+dt["year"] if int(dt["year"])<10 else dt["year"],
                "insured.sex": "1" if dt["gender"] =="M" else "2",
                "policy.amount": str(int(int(dt["money"])/10000)),
                "policy.dateRemark": "9999",
                "policy.chargeType": "1",
                "policy.chargeYear": dt["interval"].replace("y",""),
                "policy.showMessage": "true",
                "person.mobilenum": "承保短信将发送至您的手机"
            }
        else:
            print("/*~~~~月缴~~~~~~*/")

            if dt["interval"] == "120m":
                risk_code = "0110000318"
                productCode = "50000837"

            elif dt["interval"] == "180m":
                risk_code = "0110000331"
                productCode = "50000838"
            else:
                risk_code = "0110000333"
                productCode = "50000839"

            data = {

                "pageName": "productAdd",
                "goods_id": "62540",
                "merchant_id": "B2C",
                "toubaoli_money": "",
                "productCode": productCode,
                "productId": "f4bbe12e-4946-41c5-a6c2-454ee94ac339",
                "riskCode": risk_code,
                "productName": "太平金生康瑞终身重大疾病保险",
                "insuredPrice": "36.50",
                "insured.birthday": "",
                "templateType": "",
                "employee_id": "",
                "channel": "GWSC - MENU - M14",
                "empNo": "",
                "newsCode": "",
                "twoMonthInsuredPrice": "",
                "loginUserId": "",
                "insured.age": "0" + dt["year"] if int(dt["year"]) < 10 else dt["year"],
                "insured.sex": "1" if dt["gender"] == "M" else "2",
                "policy.amount": str(int(int(dt["money"]) / 10000)),
                "policy.dateRemark": "9999",
                "policy.chargeType": "4",
                "policy.chargeYear": str(int(int(dt["interval"].replace("m", ""))/12)),
                "policy.showMessage": "true",
                "person.mobilenum": "承保短信将发送至您的手机"
            }

        payload = urlencode(data).replace("+","")
        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)
        if r.status_code == 200 and "计算保费成功" in r.text:
            price = Helper.decimalParse( r.json()["totalPremium"])
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
            print("\n/*产品价格更新失败:%d*/"%dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)
